import { getToken } from "../../utils/auth";
import axios from "axios";
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from "@/utils/loading";
export default function GlobalAxiosConfig(
  apiConfigs,
  $axios,
  ctx,
  AxiosConfig,
  onRequest,
  onResponse,
  onError
) {
  const api = {};
  apiConfigs.forEach(
    ({ name, url, method, baseURL, responseType, headers }) => {
      api[name] = function (resolve, query, callback) {
        const newAxiosConfig = {
          ...AxiosConfig,
          url,
          method: method,
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            // Authorization: ctx.$auth.strategy.token.get(),
          },
          cache: {
            maxAge: 60 * 60 * 1000
          }
        };
        // console.log('ctx', ctx)
        // 拼接token
        // console.log('token', getToken())
        let token = getToken();

        // console.log("resolve", query, resolve);
        newAxiosConfig.baseURL = baseURL || newAxiosConfig.baseURL;
        newAxiosConfig.responseType =
          responseType || newAxiosConfig.responseType;
        if (headers)
          newAxiosConfig.headers = { ...newAxiosConfig.headers, ...headers };

        let urlParams;
        if (callback) newAxiosConfig.onUploadProgress = callback;

        if (method.toLowerCase() === "post" || method.toLowerCase() === "put") {
          if (token) {
            query.ak = token;
          }
          urlParams = query;
          newAxiosConfig.data = resolve;
          if (query) newAxiosConfig.params = query;
        } else {
          if (token) {
            resolve.ak = token;
          }
          urlParams = resolve;
          newAxiosConfig.params = resolve;
        }

        let isLinkParams = newAxiosConfig.url
          .replace(/(http|https):\/\/.*?\//g, "")
          .match(/:.*/g);
        if (isLinkParams) {
          if (urlParams) {
            let requestPath = newAxiosConfig.url.replace(
              /(http|https):\/\/.*?\//g,
              ""
            );

            let paramPlaceholders = requestPath.split(":");
            paramPlaceholders.forEach((m, i) => {
              let propName = m.replace(/[/|:]/g, "");
              if (urlParams[propName] != undefined) {
                newAxiosConfig.url = newAxiosConfig.url.replace(
                  ":" + propName,
                  urlParams[propName]
                );
              }
            });
          }
        }

        onRequest(newAxiosConfig);
        return new Promise((resolve, reject) => {
          $axios(newAxiosConfig)
            .then((res) => {
              if (res) {
                onResponse(res, ctx);
                resolve(res.data);
                tryHideFullScreenLoading();
              } else {
                tryHideFullScreenLoading();
                ctx.store.dispatch("user/logout");
                ctx.redirect({ name: "home" });
              }
            })
            .catch((err) => {
              tryHideFullScreenLoading();
              onError(err);
              reject(err);
            });
        });
      };
    }
  );
  return api;
}
